import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import "../../components" as Components
import "../../styles" as Styles

Rectangle {
    id: vehicleControlView

    // 自定义属性
    property var agv: null
    property var vehicleViewModel: null
    property var taskViewModel: null
    property var defaultStationOptions: ["站点A", "站点B", "站点C", "充电桩1", "充电桩2"]
    property int targetHistoryRevisionKey: vehicleViewModel ? vehicleViewModel.targetHistoryRevision : 0

    color: Styles.Theme.backgroundSecondary
    border.color: Styles.Theme.border
    border.width: 1
    radius: Styles.Theme.radiusSmall

    ColumnLayout {
        anchors.fill: parent
        anchors.margins: Styles.Theme.spacingNormal
        spacing: Styles.Theme.spacingNormal

        // 标题栏
        RowLayout {
            Layout.fillWidth: true

            Text {
                text: qsTr("控制面板")
                color: Styles.Theme.textPrimary
                font.pixelSize: Styles.Theme.fontSizeNormal
                font.weight: Styles.Theme.fontWeightMedium
                Layout.fillWidth: true
            }
        }

        ScrollView {
            id: controlScrollView
            Layout.fillWidth: true
            Layout.fillHeight: true
            clip: true

            ScrollBar.horizontal.policy: ScrollBar.AlwaysOff

            ScrollBar.vertical: ScrollBar {
                id: vbar
                width: 8
                policy: ScrollBar.AsNeeded
                anchors.right: parent.right
                anchors.top: parent.top
                anchors.bottom: parent.bottom

                contentItem: Rectangle {
                    implicitWidth: 8
                    radius: 4
                    color: vbar.pressed ? Styles.Theme.primary :
                           vbar.hovered ? Styles.Theme.textSecondary :
                           Styles.Theme.textTertiary
                    opacity: vbar.pressed ? 0.9 : vbar.hovered ? 0.7 : 0.5

                    Behavior on color { ColorAnimation { duration: 150 } }
                    Behavior on opacity { NumberAnimation { duration: 150 } }
                }

                background: Rectangle {
                    color: Styles.Theme.backgroundSecondary
                    opacity: 0.3
                    radius: 4
                }
            }

            ColumnLayout {
                width: controlScrollView.width - 12  // 为右侧滚动条留出空间 (8px + 4px margin)
                spacing: Styles.Theme.spacingNormal

                // 顶升控制区域
                Rectangle {
                    Layout.fillWidth: true
                    implicitHeight: basicControlColumn.implicitHeight + Styles.Theme.spacingNormal * 2
                    color: "transparent"
                    border.color: Styles.Theme.border
                    border.width: 1
                    radius: Styles.Theme.radiusSmall

                    ColumnLayout {
                        id: basicControlColumn
                        anchors.left: parent.left
                        anchors.right: parent.right
                        anchors.top: parent.top
                        anchors.margins: Styles.Theme.spacingNormal
                        spacing: Styles.Theme.spacingSmall

                        Text {
                            text: qsTr("顶升控制")
                            color: Styles.Theme.textPrimary
                            font.pixelSize: Styles.Theme.fontSizeSmall
                            font.weight: Styles.Theme.fontWeightMedium
                        }

                        GridLayout {
                            Layout.fillWidth: true
                            columns: 2
                            columnSpacing: Styles.Theme.spacingSmall
                            rowSpacing: Styles.Theme.spacingSmall

                            Components.ActionButton {
                                Layout.fillWidth: true
                                text: qsTr("上升")
                                iconSource: "⬆️"
                                buttonType: "primary"
                                enabled: agv && agv.status !== "offline"
                                onClicked: {
                                    if (vehicleViewModel && agv) {
                                        vehicleViewModel.controlJack(agv.agvNumber, true)
                                    }
                                }
                            }

                            Components.ActionButton {
                                Layout.fillWidth: true
                                text: qsTr("下降")
                                iconSource: "⬇️"
                                buttonType: "warning"
                                enabled: agv && agv.status !== "offline"
                                onClicked: {
                                    if (vehicleViewModel && agv) {
                                        vehicleViewModel.controlJack(agv.agvNumber, false)
                                    }
                                }
                            }
                        }
                    }
                }

                // 导航控制区域
                Rectangle {
                    Layout.fillWidth: true
                    implicitHeight: navigationControlColumn.implicitHeight + Styles.Theme.spacingNormal * 2
                    color: "transparent"
                    border.color: Styles.Theme.border
                    border.width: 1
                    radius: Styles.Theme.radiusSmall

                    ColumnLayout {
                        id: navigationControlColumn
                        anchors.left: parent.left
                        anchors.right: parent.right
                        anchors.top: parent.top
                        anchors.margins: Styles.Theme.spacingNormal
                        spacing: Styles.Theme.spacingSmall

                        Text {
                            text: qsTr("导航控制")
                            color: Styles.Theme.textPrimary
                            font.pixelSize: Styles.Theme.fontSizeSmall
                            font.weight: Styles.Theme.fontWeightMedium
                        }

                        // 目标站点选择
                        RowLayout {
                            Layout.fillWidth: true

                            Text {
                                text: qsTr("目标站点:")
                                color: Styles.Theme.textSecondary
                                font.pixelSize: Styles.Theme.fontSizeSmall
                                Layout.preferredWidth: 80
                            }

                            Components.CustomComboBox {
                                id: targetStationCombo
                                Layout.fillWidth: true
                                implicitHeight: 48
                                model: getAvailableStations()
                                enabled: agv && agv.status !== "offline"
                                placeholderText: qsTr("选择站点...")
                                textRole: "text"
                                valueRole: "value"
                            }
                        }

                        GridLayout {
                            Layout.fillWidth: true
                            columns: 2
                            columnSpacing: Styles.Theme.spacingSmall
                            rowSpacing: Styles.Theme.spacingSmall

                            Components.ActionButton {
                                Layout.fillWidth: true
                                text: qsTr("前往站点")
                                iconSource: "🎯"
                                buttonType: "primary"
                                enabled: agv && agv.status !== "offline" && targetStationCombo.currentIndex >= 0
                                onClicked: {
                                    if (vehicleViewModel && agv) {
                                        var station = targetStationCombo.currentText
                                        vehicleViewModel.goToStation(agv.agvNumber, station)
                                    }
                                }
                            }

                            Components.ActionButton {
                                Layout.fillWidth: true
                                text: qsTr("取消导航")
                                iconSource: "❌"
                                buttonType: "danger"
                                enabled: agv && agv.status === "executing"
                                onClicked: {
                                    if (vehicleViewModel && agv) {
                                        vehicleViewModel.cancelTask(agv.agvNumber)
                                    }
                                }
                            }

                            Components.ActionButton {
                                Layout.fillWidth: true
                                text: agv && agv.status === "paused" ? qsTr("继续导航") : qsTr("暂停导航")
                                iconSource: agv && agv.status === "paused" ? "▶️" : "⏸️"
                                buttonType: agv && agv.status === "paused" ? "success" : "warning"
                                enabled: agv && (agv.status === "executing" || agv.status === "paused")
                                onClicked: {
                                    if (vehicleViewModel && agv) {
                                        if (agv.status === "paused") {
                                            vehicleViewModel.resumeTask(agv.agvNumber)
                                        } else {
                                            vehicleViewModel.pauseTask(agv.agvNumber)
                                        }
                                    }
                                }
                            }

                            Components.ActionButton {
                                Layout.fillWidth: true
                                text: qsTr("前往充电")
                                iconSource: "⚡"
                                buttonType: "secondary"
                                enabled: agv && agv.status !== "offline" && agv.status !== "charging"
                                onClicked: {
                                    if (taskViewModel && agv) {
                                        const chainId = taskViewModel.createChargeTask(agv.agvNumber)
                                        if (!chainId || chainId.length === 0) {
                                            console.warn("VehicleControlView: failed to create charge task for AGV", agv.agvNumber)
                                        }
                                    } else {
                                        console.warn("VehicleControlView: TaskViewModel unavailable, cannot create charge task")
                                    }
                                }
                            }

                            Components.ActionButton {
                                Layout.fillWidth: true
                                text: qsTr("前往停车")
                                iconSource: "🅿️"
                                buttonType: "secondary"
                                enabled: agv && agv.status !== "offline"
                                onClicked: {
                                    if (taskViewModel && agv) {
                                        const chainId = taskViewModel.createParkTask(agv.agvNumber)
                                        if (!chainId || chainId.length === 0) {
                                            console.warn("VehicleControlView: failed to create park task for AGV", agv.agvNumber)
                                        }
                                    } else {
                                        console.warn("VehicleControlView: TaskViewModel unavailable, cannot create park task")
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    // 辅助函数

    function getAvailableStations() {
        const revision = targetHistoryRevisionKey
        if (!vehicleViewModel || !agv) {
            return defaultStationOptions
        }

        const cached = vehicleViewModel.getRecentTargetStations(agv.agvNumber)
        if (cached && cached.length > 0) {
            return cached
        }

        return defaultStationOptions
    }
}
